package br.com.wai2008.socket.direction;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import br.com.wai2008.context.constants.DAOConstants;

public class DirectionDAO {

	public boolean isNode(String x, String y) throws SQLException {
		Connection connection = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			connection = this.getConnection();
			stmt = connection.prepareStatement("SELECT vertexId FROM Vertex WHERE x=? AND y=?");
			stmt.setString(1, x);
			stmt.setString(2, y);
			
			rs = stmt.executeQuery();
			
			if (rs.next()) {
				return true;
			} else {
				return false;
			}
		} catch (SQLException sqle) {
			throw sqle;
		} finally {
			rs.close();
			stmt.close();
			connection.close();
		}
	}

	public String getDirection(int direction, String language) throws SQLException {
		language = "direction" + language;
		String direcao = null;
		Connection connection = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			connection = this.getConnection();
			stmt = connection.prepareStatement("SELECT " + language +  " FROM Direction WHERE directionId=?");
			stmt.setInt(1, direction);
			
			rs = stmt.executeQuery();
			
			while (rs.next()) {
				direcao = rs.getString(1);
			}
		} catch (SQLException sqle) {
			throw sqle;
		} finally {
			rs.close();
			stmt.close();
			connection.close();
		}
		return direcao;
	}
	
	private Connection getConnection() throws SQLException {
		return DriverManager.getConnection(
				DAOConstants.DATABASE_URL, DAOConstants.DATABASE_USER,
				DAOConstants.DATABASE_PASSWORD);
	}
}
